package LL7;

public class Main {

    // Definition for singly-linked list.
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    static class Solution {
        public ListNode removeElements(ListNode head, int val) {
            //1.定义虚拟头节点
            ListNode tmpHead = new ListNode(-1);
            tmpHead.next = head;
            ListNode cur = tmpHead;

            //2.删除节点
            while (cur.next != null) {
                if (cur.next.val == val) { //如果下个节点值与比较值相同，删除下个节点
                    cur.next = cur.next.next;
                } else { //如果下个节点的值不相同，则移动指针变量
                    cur = cur.next;
                }
            }
            return tmpHead.next;
        }
    }

    private static void printNode(ListNode head) {
        ListNode cur = head;
        //遍历每一个节点
        while (cur != null) {
            System.out.print(cur.val + "\t");
            cur = cur.next;//移动指针变量
        }
        System.out.println();
    }
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(6);
        head.next.next.next = new ListNode(3);
        head.next.next.next.next = new ListNode(4);
        head.next.next.next.next.next = new ListNode(5);
        head.next.next.next.next.next.next = new ListNode(6);
        printNode(head);

        Solution solution = new Solution();
        ListNode listNode = solution.removeElements(head, 6);
        printNode(listNode);
    }
}
